export default class Edge {
  constructor(options = {}) {
    this.id = options.id || `edge-${Date.now()}`
    this.sourceNodeId = options.sourceNodeId
    this.sourceAnchorId = options.sourceAnchorId
    this.targetNodeId = options.targetNodeId
    this.targetAnchorId = options.targetAnchorId
    this.color = options.color || '#666'
    this.width = options.width || 2
    this.showArrow = options.showArrow !== undefined ? options.showArrow : true
    this.selected = false
    this.path = ''
    this.arrowHead = { x: 0, y: 0 }
  }

  // 更新路径
  updatePath(nodes) {
    const sourceNode = nodes.get(this.sourceNodeId)
    const targetNode = nodes.get(this.targetNodeId)

    if (!sourceNode || !targetNode) {
      this.path = ''
      return
    }

    const sourceAnchor = sourceNode.getAnchor(this.sourceAnchorId)
    const targetAnchor = targetNode.getAnchor(this.targetAnchorId)

    if (!sourceAnchor || !targetAnchor) {
      this.path = ''
      return
    }

    // 计算绝对坐标
    const sourceX = sourceNode.x + sourceAnchor.x
    const sourceY = sourceNode.y + sourceAnchor.y
    const targetX = targetNode.x + targetAnchor.x
    const targetY = targetNode.y + targetAnchor.y

    // 计算控制点（简单的贝塞尔曲线）
    const controlX1 = sourceX + (targetX - sourceX) / 3
    const controlY1 = sourceY
    const controlX2 = targetX - (targetX - sourceX) / 3
    const controlY2 = targetY

    // 生成路径
    this.path = `M ${sourceX} ${sourceY} C ${controlX1} ${controlY1}, ${controlX2} ${controlY2}, ${targetX} ${targetY}`

    // 计算箭头位置
    if (this.showArrow) {
      this.calculateArrowHead(sourceX, sourceY, targetX, targetY)
    }
  }

  // 计算箭头位置
  calculateArrowHead(sourceX, sourceY, targetX, targetY) {
    // 箭头大小
    const arrowSize = 10

    // 计算方向向量
    const dx = targetX - sourceX
    const dy = targetY - sourceY
    const length = Math.sqrt(dx * dx + dy * dy)
    const unitDx = dx / length
    const unitDy = dy / length

    // 计算箭头位置（稍微回退一点，避免箭头超出目标点）
    this.arrowHead.x = targetX - unitDx * arrowSize
    this.arrowHead.y = targetY - unitDy * arrowSize
  }

  // 转换为JSON
  toJSON() {
    return {
      id: this.id,
      sourceNodeId: this.sourceNodeId,
      sourceAnchorId: this.sourceAnchorId,
      targetNodeId: this.targetNodeId,
      targetAnchorId: this.targetAnchorId,
      color: this.color,
      width: this.width,
      showArrow: this.showArrow
    }
  }
}